import axios from 'axios'
import qs from 'qs'

const service = axios.create({
  baseURL: 'http://localhost:8000',
  timeout: 5000
})

// 请求拦截：自动带 token
service.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    // 登录接口需要表单格式
    if (config.url === '/token') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => Promise.reject(error)
)

// 响应拦截：401 统一处理
service.interceptors.response.use(
  res => res.data,
  err => {
    if (err.response && err.response.status === 401) {
      localStorage.removeItem('token')
      // 防止无限循环
      if (router.currentRoute.path !== '/login') {
        router.push('/login')
      }
    }
    return Promise.reject(err)
  }
)

export default service